package com.cxj.cxj_test_cloud.common.rxjava;

import android.net.ParseException;
import android.widget.Toast;

import com.cxj.cxj_test_cloud.utils.Logger;
import com.cxj.cxj_test_cloud.utils.ToastUtil;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.subscribers.DisposableSubscriber;
import retrofit2.HttpException;

/**
 * Rxjava请求回调公共处理类
 * @param <T>
 */
public abstract class MvvmResponseSubscriber<T> extends DisposableSubscriber<T> {
    public final static int LOCAL_ERROR = 4004;//本地解析之类的错误
    public final static int NETWORK_UNAVAILABLE = 4005;//网络不可用
    public final static int REQUEST_TIMEOUT = 4006;//网络请求超时

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    public void onNext(T t) {

    }

    @Override
    public void onError(Throwable t) {
        try {
            handleResponseError(t);
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    /**
     * 错误类型解析
     * @param t
     */
    private void handleResponseError(Throwable t) {
        String msg="未知错误";
        int code=LOCAL_ERROR;
        if (t instanceof UnknownHostException){
            msg="网络不可用";
            code=NETWORK_UNAVAILABLE;
        }else if (t instanceof SocketTimeoutException){
            msg="网络请求超时";
            code=REQUEST_TIMEOUT;
        } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException || t instanceof ClassCastException) {
            msg= "数据解析错误,请尝试重启应用!";
            code=LOCAL_ERROR;
        } else if (t instanceof HttpException) {
            HttpException httpException = (HttpException) t;
            msg = convertStatusCode(httpException);
            code = httpException.code();
        }
        //主线程显示toast
        ToastUtil.show(msg);

        //打印日志
        Logger.e(t);

        t.printStackTrace();

        //业务层按需要处理，不需要处理可忽略
        onError(code, msg);
    }

    /**
     * 服务端错误解析
     * @param httpException
     * @return
     */
    private String convertStatusCode(HttpException httpException) {
        String msg;
        if (httpException.code() == 500){
            msg = "服务器发生错误";
        } else if (httpException.code() == 404) {
            msg = "请求地址错误";
        } else if (httpException.code() == 403) {
            msg="拒绝访问";
        }else if (httpException.code() == 307){
            msg = "请求被重定向到其他页面";
        }else {
            msg=httpException.getMessage();
        }
        return msg;
    }

    @Override
    public void onComplete() {

    }

    public abstract void onSuccess(T response);
    public abstract void onError(int errorCode, String error);
}
